package com.magicmovie.api.controller;

import com.google.common.collect.Maps;
import com.magicmovie.api.service.OrderService;
import com.magicmovie.entity.Customer;
import com.magicmovie.entity.Order;
import com.magicmovie.shiro.CurrentCustomerService;
import com.magicmovie.util.common.AjaxMsg;
import com.magicmovie.util.common.ValidUtil;
import com.magicmovie.util.exception.CustomException;
import com.magicmovie.util.pay.PaySaPi;
import com.magicmovie.util.pay.PayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Map;

@RestController()
@RequestMapping("/api")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private CurrentCustomerService currentCustomerService;
    @Value("${paysapi.uid}")
    private String UID;
    @Value("${paysapi.token}")
    private String TOKEN;
//    @Value("${paysapi.return_url}")
//    private String RETURN_URL;
    @Value("${paysapi.notify_url}")
    private String NOTIFY_URL;

    @RequestMapping(value = "/order/createOrder", method = RequestMethod.POST)
    public AjaxMsg createOrder(HttpServletRequest request, String price, @RequestParam(required = false) Integer movieId, String payType,String url,String returnUrl) {
        if (ValidUtil.isEmpty(price, payType))
            return new AjaxMsg(AjaxMsg.FAILURE, "参数不能为空！");
        Customer customer = currentCustomerService.getCurrentCustomer();
        if(movieId != null){
            Order order = orderService.findByUidAndMovieId(customer.getId(), movieId);
            if(order != null && order.getStatus().equals("01"))
                return new AjaxMsg(AjaxMsg.FAILURE,"已经购买该电影，请勿重复购买！");
        }

//        StringBuffer url = request.getRequestURL();
//        String site = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
        //创建订单
        String orderNum = orderService.crateOrder(Float.valueOf(price), payType, url, customer.getId(), movieId);

        if (payType.equals("01"))
            return new AjaxMsg(orderNum);

        Map<String, Object> result = Maps.newHashMap();
        result.put("uid", UID);
        result.put("price", price);
        if (payType.equals("02"))
            result.put("istype", 1);
        if (payType.equals("03"))
            result.put("istype", 2);
        result.put("notify_url", NOTIFY_URL);
        result.put("return_url", returnUrl);
        result.put("orderid", orderNum);

        //生成key
        String key = "";
        try {
            key = PayUtil.getKey(result, TOKEN);
        } catch (UnsupportedEncodingException e) {
            throw new CustomException("paysApi key 生成失败!");
        }
        result.put("key", key);
        return new AjaxMsg(result);
    }

    /**
     * paysApi支付回调
     * @param request
     * @param response
     * @param paySaPi
     */
    @RequestMapping("/order/payNotify")
    public void notifyPay(HttpServletRequest request, HttpServletResponse response, PaySaPi paySaPi) {
        // 保证密钥一致性
        try {
            if (PayUtil.checkPayKey(paySaPi, TOKEN)) {
                // TODO 做自己想做的
                Order order = orderService.findByOrderNum(paySaPi.getOrderid());
                if(order!=null && order.getStatus().equals("00")){
                    order.setPayCode(paySaPi.getPaysapi_id());
                    orderService.updateOrderStatus(order);
                }
            } else {
                // TODO 该怎么做就怎么做
                throw new CustomException("paysApi 回调 校验失败！");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new CustomException("PaysApi 校验出错！");
        }
    }

    @RequestMapping(value = "/order/status",method = RequestMethod.GET)
    public AjaxMsg orderStatus(String orderNum){
        if(ValidUtil.isEmpty(orderNum))
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空！");
        Order order = orderService.findByOrderNum(orderNum);
        if(order == null)
            return new AjaxMsg(AjaxMsg.FAILURE,"订单不存在！");
        return new AjaxMsg(order.getStatus());
    }

    /**
     * 确认余额支付
     * @param orderNum
     * @return
     */
    @RequestMapping(value = "/order/balancePayment",method = RequestMethod.POST)
    public AjaxMsg payByBalance(String orderNum){
        if(ValidUtil.isEmpty(orderNum))
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空！");
        Order order = orderService.findByOrderNum(orderNum);
        if(order == null)
            return new AjaxMsg(AjaxMsg.FAILURE,"订单不存在！");
        Customer customer = currentCustomerService.getCurrentCustomer();
        if(customer.getBalance() < order.getPrice())
            return new AjaxMsg(AjaxMsg.FAILURE,"余额不足，请充值！");
        orderService.payByBalance(order);
        return new AjaxMsg();
    }
}


